<?php

namespace App\Http\Controllers\CRM;

use App\Enums\OrderItemType;
use App\Enums\TradeStatus;
use App\Enums\UserType;
use App\Helper\ApiResponseHelper;
use App\Http\Controllers\Controller;
use App\Http\Resources\CRM\Report\MemberMoneyResource;
use App\Models\Game;
use App\Models\Goods;
use App\Models\Member;
use App\Models\MemberMoneyLog;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Table;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ReportDataController extends Controller
{
    public function memberMoneyLogs(Request $request)
    {
        [$startAt, $endAt] = $this->getStartAndEnd($request);
        $storeId = $request->input('store_id');

        $query = MemberMoneyLog::whereBetween('created_at', [$startAt, $endAt])
            ->with([
                'member.registerStore', 'user.store'
            ])
            ->orderBy('created_at', 'desc');
        if (!empty($storeId))
            $query = $query->where('store_id', $storeId);

        $logs = $query->get();

        return MemberMoneyResource::collection($logs);
    }

    //营业报表
    public function businessReport(Request $request)
    {
        [$startAt, $endAt] = $this->getStartAndEnd($request);
        $storeId = $request->store_id;

        $data = [
            //客单数
            'order_count' => 0,
            //营业额
            'turnover' => 0,
            //台桌总额
            'table_turnover' => 0,
            //助教总额
            'assistant_turnover' => 0,
            //助教买课总额
            'assistant_buy_turnover' => 0,
            //商品总额
            'goods_turnover' => 0,
        ];

        $orderQuery = Order::whereBetween('created_at', [$startAt, $endAt])
            ->where('status', TradeStatus::Payed)
            ->where('store_id', $storeId);

        $data['order_count'] = $orderQuery->count();
        $data['turnover'] = $orderQuery->sum('money');

        $orderIds = $orderQuery->pluck('id');
        $data['table_turnover'] = OrderItem::whereIn('order_id', $orderIds)
            ->where('type', OrderItemType::Table)
            ->sum('money');

        $data['assistant_turnover'] = OrderItem::whereIn('order_id', $orderIds)
            ->where('type', OrderItemType::Assistant)
            ->sum('money');

        $data['goods_turnover'] = OrderItem::whereIn('order_id', $orderIds)
            ->where('type', OrderItemType::Goods)
            ->sum('money');

        return ApiResponseHelper::json($data);
    }

    //台桌报表
    public function tableReport(Request $request)
    {
        [$startAt, $endAt] = $this->getStartAndEnd($request);
        $storeId = $request->store_id;

        $data = [
            //台桌名
            'table_name' => '',
            //台桌区域
            'table_area' => '',
            //台桌品牌名称
            'table_brand_name' => '',
            //订单数量
            'order_count' => 0,
            //真实时长
            'real_time' => 0,
            //原始时长
            'origin_time' => 0,
            //优惠时长
            'discount_time' => 0,
            //支付时长
            'pay_time' => 0,
            //退款时长
            'refund_time' => 0,
            //营业时长
            'business_time' => 0,
            //平均时长
            'average_time' => 0,
            //台桌总额
            'table_turnover' => 0,
            //商品金额
            'goods_turnover' => 0,
        ];

        $tables = Table::with([
            'tableType'
        ])->whereHas('tableType', function ($query) use ($storeId) {
            $query->where('store_id', $storeId);
        })->get();

        $res = [];
        foreach ($tables as $table) {

            $buf = $data;
            $buf['table_name'] = $table->getName();
            $buf['table_area'] = $table->tableType->type;
            $buf['table_brand_name'] = $table->tableType->name;
            $orderQuery = Order::whereBetween('created_at', [$startAt, $endAt])
                ->where('status', TradeStatus::Payed)
                ->where('store_id', $storeId)
                ->whereHas('items', function ($query) use ($table) {
                    $query->where('type', OrderItemType::Table)
                        ->where('table_id', $table->id);
                });
            $orderIds = $orderQuery->pluck('id');
            $buf['order_count'] = OrderItem::whereIn('order_id', $orderIds)
                ->where('type', OrderItemType::Table)
//                ->where('table_id', $table->id)
                ->count();
            //计算OrderItem start_at 和 end_at 之间的时间差，单位分钟
            $timeQuery = OrderItem::whereIn('order_id', $orderIds)
                ->where('type', OrderItemType::Table)
//                ->where('table_id', $table->id)
                ->select(DB::raw('SUM(TIMESTAMPDIFF(MINUTE, start_at, end_at)) as total_minutes'));

            $buf['real_time'] = $timeQuery->where('is_virtual', false)
                ->value('total_minutes') ?? 0;
            $buf['origin_time'] = $timeQuery->value('total_minutes') ?? 0;
            $buf['pay_time'] = $buf['origin_time'];
            $buf['business_time'] = $buf['origin_time'];
            $buf['average_time'] = $buf['order_count'] > 0 ? $buf['real_time'] / $buf['order_count'] : 0;
            $buf['table_turnover'] = OrderItem::whereIn('order_id', $orderIds)
                ->where('type', OrderItemType::Table)
//                ->where('table_id', $table->id)
                ->sum('money');

            $buf['goods_turnover'] = OrderItem::whereIn('order_id', $orderIds)
                ->where('type', OrderItemType::Goods)
                ->sum('money');

            $res[] = $buf;
        }

        return ApiResponseHelper::json($res);
    }

    //助教报表
    public function assistantReport(Request $request)
    {
        [$startAt, $endAt] = $this->getStartAndEnd($request);
        $storeId = $request->store_id;

        $data = [
            //助教名
            'assistant_name' => '',
            //助教分类
            'assistant_type' => '',
            //订单数量
            'order_count' => 0,
            //真实时长
            'real_time' => 0,
            //原始时长
            'origin_time' => 0,
            //优惠时长
            'discount_time' => 0,
            //退款时长
            'refund_time' => 0,
            //买课时长
            'buy_time' => 0,
            //买课优惠时长
            'buy_discount_time' => 0,
            //上课时长
            'teach_time' => 0,
            //上课优惠时长
            'teach_discount_time' => 0,
            //上课退款时长
            'teach_refund_time' => 0,
            //假休时长
            'rest_time' => 0,
            //假休退款时长
            'rest_refund_time' => 0,
        ];

        $assistants = User::withType(UserType::Assistant)->where('store_id', $storeId)->get();

        $res = [];
        foreach ($assistants as $assistant) {

            $buf = $data;
            $buf['assistant_name'] = $assistant->name;
            $buf['assistant_type'] = $assistant->role->name;
            $orderQuery = Order::whereBetween('created_at', [$startAt, $endAt])
                ->where('status', TradeStatus::Payed)
                ->where('store_id', $storeId)
                ->whereHas('items', function ($query) use ($assistant) {
                    $query->where('type', OrderItemType::Assistant)
                        ->where('assistant_user_id', $assistant->id);
                });
            $orderIds = $orderQuery->pluck('id');
            $buf['order_count'] = $orderQuery->count();
            //计算OrderItem start_at 和 end_at 之间的时间差，单位分钟
            $timeQuery = OrderItem::whereIn('order_id', $orderIds)
                ->where('type', OrderItemType::Assistant)
                ->where('assistant_user_id', $assistant->id)
                ->select(DB::raw('SUM(TIMESTAMPDIFF(MINUTE, start_at, end_at)) as total_minutes'));

            $buf['real_time'] = $timeQuery->where('is_virtual', false)->value('total_minutes') ?? 0;
            $buf['origin_time'] = $timeQuery->value('total_minutes') ?? 0;

            $res[] = $buf;
        }

        return ApiResponseHelper::json($res);
    }

    //会员报表
    public function memberReport(Request $request)
    {
        [$startAt, $endAt] = $this->getStartAndEnd($request);
        $storeId = $request->store_id;
    }

    //订单报表
    public function orderReport(Request $request)
    {
        [$startAt, $endAt] = $this->getStartAndEnd($request);
        $storeId = $request->store_id;

        $data = [
            //商品名称
            'goods_name' => '',
            //营收总额
            'turnover' => 0,
            //分类名称
            'category_name' => '',
            //单位
            'unit' => '',
            //订单数量
            'order_count' => 0,
            //销售数量
            'sale_count' => 0,
            //退款数量
            'refund_count' => 0,
            //优惠总额
            'discount_money' => 0,
            //支付总额
            'pay_money' => 0,
            //毛利总额
            'gross_profit' => 0,
        ];

        $goods = Goods::with(['category'])->get();

        $res = [];
        foreach ($goods as $good) {

            $buf = $data;
            $buf['goods_name'] = $good->name;
            $buf['category_name'] = $good->category->name;
            $buf['unit'] = $good->unit;
            $orderQuery = Order::whereBetween('created_at', [$startAt, $endAt])
                ->where('status', TradeStatus::Payed)
                ->where('store_id', $storeId)
                ->whereHas('items', function ($query) use ($good) {
                    $query->where('type', OrderItemType::Goods)
                        ->where('goods_id', $good->id);
                });
            $orderIds = $orderQuery->pluck('id');
            $orderItemQuery = OrderItem::whereIn('order_id', $orderIds)
                ->where('type', OrderItemType::Goods);
            $buf['turnover'] = $orderItemQuery->sum('money');
            $buf['order_count'] = $orderQuery->count();
            $buf['sale_count'] = $orderItemQuery->sum('count');
            $buf['pay_money'] = $orderItemQuery->sum('money');
            $cost = $good->purchase_cost_price + $good->sale_cost_price;
            $buf['gross_profit'] = $buf['pay_money'] - $cost * $buf['sale_count'];

            $res[] = $buf;
        }

        return ApiResponseHelper::json($res);
    }

    //比赛报表
    public function matchReport(Request $request)
    {
        [$startAt, $endAt] = $this->getStartAndEnd($request);
        $storeId = $request->store_id;

        $data = [
            //比赛名称
            'match_name' => '',
            //比赛时间
            'match_date' => '',
            //参与人数
            'join_count' => 0,
            //冠军
            'champion' => '',
            //亚军
            'runner_up' => '',
            //季军
            'third_place' => '',
        ];

        $games = Game::whereBetween('game_start_date', [$startAt, $endAt])
//            ->where('store_id', $storeId)
            ->get();

        $res = [];
        foreach ($games as $game) {

            $signUsers = $game->users()->orderBy('point', 'desc')->get();
            $buf = $data;

            $buf['match_name'] = $game->name;
            $buf['match_date'] = $game->game_start_date;
            $buf['join_count'] = $signUsers->count();
            $buf['champion'] = $signUsers->first()->member->name;
            $buf['runner_up'] = $signUsers->skip(1)->first()->member->name;
            $buf['third_place'] = $signUsers->skip(2)->first()->member->name;

            $res[] = $buf;
        }

        return ApiResponseHelper::json($res);
    }

    //积分报表
    public function pointReport(Request $request)
    {
        [$startAt, $endAt] = $this->getStartAndEnd($request);
        $storeId = $request->store_id;

        $data = [
            //名字
            'name' => '',
            //手机号
            'phone' => '',
            //新增积分
            'add_point' => 0,
            //途径
            'way' => '',
            //操作前积分
            'before_point' => 0,
            //操作后积分
            'after_point' => 0,
            //剩余积分
            'remain_point' => 0,
        ];

        return ApiResponseHelper::json([]);
    }

    //工作报表
    public function workReport(Request $request)
    {
        [$startAt, $endAt] = $this->getStartAndEnd($request);
        $storeId = $request->store_id;

        $data = [
            //员工名字
            'name' => '',
            //岗位
            'role' => '',
            //工作内容
            'content' => '',
        ];

        return ApiResponseHelper::json([]);
    }

    private function getStartAndEnd(Request $request)
    {
        $startAt = $request->start_at;
        $endAt = $request->end_at;

        if (empty($startAt) || empty($endAt)) {
            $startAt = now()->firstOfMonth()->toDateString();
            $endAt = now()->toDateString();
        }

        $startAt = $startAt . ' 00:00:00';
        $endAt = $endAt . ' 23:59:59';

        return [$startAt, $endAt];
    }
}
